const router = require('koa-router')()
const cc = require('./conCtl')
const db = require('./dbCtl');
const jsCtl = require('./jsCtl');

/**
@hostpath = http://127.0.0.1/_test
@jwttoken = Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzLCJpYXQiOjE1OTk0MDk2ODUsImV4cCI6MTU5OTQxMzI4NX0.TZ8DKcRiW97JZ3WNt-4EohVc5u7qx7WE8MfwcJCclN0
 */
router.prefix('/_test');

/** 数据库测试 **************************************************************************/
/** 查询数据
###
    GET {{hostpath}}/db
    Authorization: {{jwttoken}}
### */
router.get('/db', async c => {  //查询用户表
    //sql对象写法
    cc.log(111);
    let data = await db.model('`t_users`').select();
    cc.log(333);
    cc.send(c, data);

    return;

    //sql语句写法
    let data2 = await db.start('SELECT * FROM `t_users`');
    cc.send(c, data2)
})
/** 查询数据并向客户端发送首行
###
    GET {{hostpath}}/db1
    Authorization: {{jwttoken}}
### */
router.get('/db1', async c => { //查询手机分类下的第一个品牌
    //sql对象写法
    let type_id = await db
        .model('`t_type_brand_model`').field('`id`')
        .where('`level`=0&&`name`=?', '手机').shift('没有找到手机分类', 'id');
    let data = await db
        .model('`t_type_brand_model`')
        .where('`parent_id`=?', type_id).shift('该分类下没有手机');
    cc.send(c, data);

    return;

    //sql语句写法
    let typeid = await db.shift('没有找到手机分类', 'id', 'SELECT `id` FROM `t_type_brand_model` where `level`=0 AND `name`=?', ['手机']);
    let data2 = await db.shift('', '', 'SELECT * FROM `t_type_brand_model` where `parent_id`=? ORDER BY `sort_index`', [typeid]);
    cc.send(c, data2);
})
/** 以数据库事务方式执行多条查询语句,任意一条执行失败,都会全部回滚
###
    GET {{hostpath}}/db2
    Authorization: {{jwttoken}}
### */
router.get('/db2', async c => {
    //sql对象写法
    await db.startTransaction(async (tran) => {
        let user_info = await tran.model('`t_users`').where('`openid`=?', '999').shift('没有找到用户');
        let admin_info = await tran.model('`t_admin`').select();
        cc.send(c, { user_info, admin_info });
    })

    return;

    //sql语句写法
    await db.startTransaction(async (tran) => {
        let userInfo = await tran.shift('没有找到用户', '', 'SELECT * FROM `t_users` where `openid`=?', ['999']);
        let adminInfo = await tran.start('SELECT * FROM `t_admin`');
        cc.send(c, { userInfo, adminInfo });
    })
})
/** 优先从缓存读取数据,如果没有缓存,会先执行一次物理查询
###
    GET {{hostpath}}/db3
    Authorization: {{jwttoken}}
### */
router.get('/db3', async c => {
    //sql对象写法
    let data = await db.model('`t_users`', { store: 'store.t_users' }).shift();
    cc.send(c, data);

    return;

    //sql语句写法
    let dbObj = await db.shift('SELECT * FROM `t_users`', { store: 'store.t_users' });
    cc.send(c, dbObj);
})
/** 删除数据库缓存
###
    GET {{hostpath}}/db4
    Authorization: {{jwttoken}}
### */
router.get('/db4', async c => {
    db.destroyStore('store.t_users');
    cc.send(c);
})

/** 插入
###
    GET {{hostpath}}/db5
    Authorization: {{jwttoken}}
### */
router.get('/db5', async c => {
    let lastID = await db.model('t_admin')
        .insert({ account: '999', pwd: 'pwd999', nick: 'dd' });
    cc.send(c, { id: lastID });
});
/** 批量插入
###
    GET {{hostpath}}/db6
    Authorization: {{jwttoken}}
### */
router.get('/db6', async c => {
    //批量插入中,返回的lastID=第一条数据的id
    //本测试中为999的id
    let postData = [
        { account: '999', pwd: 'pwd999', nick: 'dd' },
        { account: '998', pwd: 'pwd998', nick: 'dd' },
        { account: '997', pwd: 'pwd997', nick: 'dd' }]
    let lastID = await db.model('`t_admin`').insert(postData);
    cc.send(c, { id: lastID });
});
/** 更新
###
    GET {{hostpath}}/db7
    Authorization: {{jwttoken}}
### */
router.get('/db7', async c => {
    await db.model('`t_admin`').where('`account`=?', '997').update({ nick: 'dd九九七' });
    cc.send(c);
});
/** 删除
###
    GET {{hostpath}}/db8
    Authorization: {{jwttoken}}
### */
router.get('/db8', async c => {
    await db.model('`t_admin`').where('`nick` like ?', 'dd%').delete();
    cc.send(c);
});
/** 插入或更新
###
    GET {{hostpath}}/db9
    Authorization: {{jwttoken}}
### */
router.get('/db9', async c => {
    //以PRIMARY键或者UNIQUE键为判断依据,更新或插入数据
    let lastID = await db.model('t_admin')
        .insertOrUpdate({ account: '99999', pwd: 'pwd999', nick: 'ddddd' });
    cc.send(c, { id: lastID });
});






/** 登录验证测试 session **************************************************************************/
/** session中保存用户信息
###
    GET {{hostpath}}/authinit?uname=test_user&pwd=testuserpassword
### */
router.get('/authinit', async c => {
    cc.check_params(
        !c.query.uname && '!用户名' ||
        !c.query.pwd && '!密码');
    cc.auth_sess_init(c, 123, (2 | 4));
    cc.send(c, { 'youName': c.query.uname, 'youPwd': c.query.pwd });
})

/** 使用session验证权限
###
    GET {{hostpath}}/auth
### */
router.get('/auth', cc.auth_sess(2), async c => {
    cc.send(c, "ok");
})

/** 登录验证测试 jwt **************************************************************************/
/** 签发token
###
    POST {{hostpath}}/authsign
    Content-Type: application/json

    {
        "uname":"test_user",
        "pwd":"testuserpassword"
    }
### */
router.post('/authsign', async c => {
    cc.check_params(
        !c.request.body.uname && '!用户名' ||
        !c.request.body.pwd && '!密码');
    let token = cc.auth_jwt_sign(123, (2 | 4));
    cc.send(c, { 'youName': c.request.body.uname, 'youPwd': c.request.body.pwd, 'youToken': token });
})
/** 使用jwt验证权限
###
    POST {{hostpath}}/jwt
    content-type: application/json
    Authorization: {{jwttoken}}
### */
router.post('/jwt', cc.auth_jwt(2), async c => {
    cc.send(c, 'okk');
})
/** 尝试刷新token
###
    POST {{hostpath}}/jwt_new
    content-type: application/json
    Authorization: {{jwttoken}}
### */
router.post('/jwt_new', async c => {
    let new_token = cc.auth_jwt_refresh(c);
    cc.send(c, { new_token });
})
/** 强制刷新token
###
    POST {{hostpath}}/jwt_newnew
    content-type: application/json
    Authorization: {{jwttoken}}
### */
router.post('/jwt_newnew', async c => {
    let new_token = cc.auth_jwt_refresh(c, true);
    cc.send(c, { new_token });
})


/** 文件上传测试 **************************************************************************/
router.post('/upload', cc.save_img, async c => {
    console.log('abc')

    //返回上传结果
    cc.send(c, {
        upload_files: c.upload_files,
        upload_files_field: c.upload_files_field
    })
})


/** 测试
###
    POST {{hostpath}}/abc
    Content-Type: application/json

    {
        "auction_id":"88"
    }
### */
router.post('/abc', async c => {
    let data = [];
    //获取当前竞拍活动中所有竞拍商品
    let auction_goods = await db.model('t_auction_goods').where('auction_id=?', c.request.body.auction_id).field('auction_goods_id').select();
    for (let i = 0; i < auction_goods.length; i++) {
        const goods_id = auction_goods[i];
        //当前竞拍商品中拍用户openid
        let winner_openid = await db.model('t_auction_goods').where('state=3&&auction_goods_id=?&&winner_type=0&&final_price!=0', goods_id.auction_goods_id).shift('', 'winner_openid');
        //判断当前竞拍商品有无人中拍
        if (!js.isNullOrUndefined(winner_openid.winner_openid)) {//有
            //未中拍
            data = await db.model('t_bond').where('auction_goods_id=?&&state=1&&openid!=?', goods_id.auction_goods_id, winner_openid).select();//获取当前竞拍商品已缴纳保证金且未中拍的用户数据
            //中拍已支付
            data1 = await db.model('t_order').where('openid=?&&(state<>1&&state<>5)',winner_openid).shift();
        } else {//没有
            //未中拍
            data = await db.model('t_bond').where('auction_goods_id=?&&state=1', goods_id.auction_goods_id).select();//获取当前竞拍商品已缴纳保证金且未中拍的用户数据
        }

    }
    cc.send(c, { auction_goods, data });
})




module.exports = router